package com.cryptoneedle.center.source.config;


import com.cryptoneedle.center.config.helper.ConfigPropertyHelper;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManagerBuilder;
import org.apache.hc.client5.http.io.HttpClientConnectionManager;
import org.apache.hc.client5.http.ssl.SSLConnectionSocketFactory;
import org.apache.hc.client5.http.ssl.SSLConnectionSocketFactoryBuilder;
import org.apache.hc.core5.ssl.SSLContextBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

import javax.net.ssl.SSLContext;

/**
 * <p>description:  </p>
 *
 * @author CryptoNeedle
 * @date 2025-11-05
 */
@Configuration
public class RestTemplateConfig {

    @Bean
    public RestTemplate restTemplate() throws Exception {
        // 创建信任所有证书的 SSL 上下文
        SSLContext sslContext = SSLContextBuilder.create()
                .loadTrustMaterial(null, (chain, authType) -> true)
                .build();

        // 创建 SSL 连接工厂
        SSLConnectionSocketFactory sslSocketFactory = SSLConnectionSocketFactoryBuilder.create()
                .setSslContext(sslContext)
                .setHostnameVerifier((hostname, session) -> true)
                .build();

        // 创建连接管理器
        HttpClientConnectionManager connectionManager = PoolingHttpClientConnectionManagerBuilder.create()
                .setSSLSocketFactory(sslSocketFactory)
                .build();

        // 创建 HttpClient
        CloseableHttpClient httpClient = HttpClients.custom()
                .setConnectionManager(connectionManager)
                .build();

        // 创建请求工厂
        HttpComponentsClientHttpRequestFactory requestFactory =
                new HttpComponentsClientHttpRequestFactory(httpClient);
        requestFactory.setConnectTimeout(10000);

        RestTemplate restTemplate = new RestTemplate(requestFactory);
        if (ConfigPropertyHelper.dsToken() != null && !ConfigPropertyHelper.dsToken().isEmpty()) {
            ClientHttpRequestInterceptor tokenInterceptor = (request, body, execution) -> {
                request.getHeaders().add("token", ConfigPropertyHelper.dsToken());
                return execution.execute(request, body);
            };
            restTemplate.getInterceptors().add(tokenInterceptor);
        }

        return restTemplate;
    }
}